import * as Koa from 'koa';
import * as koaBody from 'koa-body';
import * as cors from '@koa/cors';
import * as dotenv from 'dotenv';
dotenv.config();
const serve = require('koa-static');
const koaValidator = require('koa-async-validator');
const koaSwagger = require('koa2-swagger-ui');
const koaBunyanLogger = require('koa-bunyan-logger');
import catcherror from './middleware/catcherror';
import auth from './middleware/auth';
import { MONGODB, config } from './config';
import routes from './helper/routes';
import * as supertest from 'superagent';
import instance from './common/instance';
import { logger } from './helper/logger';
import { log } from './common/utils';
import connect from './helper/database';


const app = new Koa();

const agent = supertest.agent();
instance.agent = agent;

app.use(koaBody({
  multipart: true,
  formLimit: "10mb",
  jsonLimit: "10mb",
  textLimit: "10mb"
}));
app.use(koaValidator());
app.use(cors());
app.use(catcherror()); // 全局错误捕捉
app.use(koaBunyanLogger(logger));
// app.use(koaBunyanLogger.requestLogger());
app.use(koaBunyanLogger.timeContext());

// app.use(routes);
app.use(serve('public'));
app.use(
  koaSwagger({
    routePrefix: '/swagger',
    swaggerOptions: {
      url: '/swagger.yml'
    }
  })
);

routes().then(r => {
  app.use(auth); // 鉴权
  app.use(r.call);

  app.listen(config.port, '0.0.0.0');

  log(`Server running on http://127.0.0.1:${config.port}/healthcheck`);

  connect({ db: `mongodb://${MONGODB.user}:${MONGODB.password}@${MONGODB.host}/${MONGODB.database}` });
});